package com.qubuyer.business.auth.view

import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.text.InputType
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.widget.doAfterTextChanged
import com.qubuyer.R
import com.qubuyer.base.AM
import com.qubuyer.business.auth.viewmodel.LoginViewModel
import com.qubuyer.constant.AppConstant
import com.qubuyer.constant.NetConstant
import com.qubuyer.core.app.MVVMActivity
import com.qubuyer.customview.BrowserActivity
import com.qubuyer.databinding.ActivityLoginBinding
import com.qubuyer.events.WeChatAuthEvent
import com.qubuyer.utils.SpanBuilder
import com.qubuyer.utils.StatusBarUtil
import com.tencent.connect.common.Constants
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.tencent.tauth.IUiListener
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.json.JSONException
import org.json.JSONObject

class LoginActivity : MVVMActivity<ActivityLoginBinding, LoginViewModel>() {
    //选中的绑定第三方类型 0:微信 1:QQ
    private var mSelectedBindType = -1

    override val viewModel: LoginViewModel by injectVMByActivity()

    override val layoutId: Int
        get() = R.layout.activity_login

    //选中的第三方openid
    private var mSelectedBindOpenId: String? = null
    private var mListener: BaseUiListener? = null
    private var inCountDown = false
    private val wxApi: Lazy<IWXAPI> = lazy {
        WXAPIFactory.createWXAPI(application, AppConstant.WECHAT_APP_ID, false).also {
            it.registerApp(AppConstant.WECHAT_APP_ID)
        }
    }

    override fun onDataBind(dataBinding: ActivityLoginBinding) {
        dataBinding.host = this
        dataBinding.vm = viewModel
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val layoutParams = dataBinding.ivClose.layoutParams as ViewGroup.MarginLayoutParams
        layoutParams.topMargin += StatusBarUtil.getStatusBarHeight()
        dataBinding.ivClose.layoutParams = layoutParams
        StatusBarUtil.setStatusBarLightMode(this, true)
        mListener = BaseUiListener()
        SpanBuilder().append("未注册的手机号验证后将自动创建趣买买账号，登录即代表您已经同意")
                .append("《趣买买用户隐私政策》", null, ContextCompat.getColor(this, android.R.color.holo_blue_light))
                .into(dataBinding.tvProtocol)


        dataBinding.etMobile.doAfterTextChanged {
            dataBinding.ivDelMobile.isVisible = !it.isNullOrEmpty()
            if (viewModel.accountLoginType.value == true) {
                dataBinding.tvLogin.isEnabled = !it.isNullOrEmpty() && dataBinding.etCode.length() > 0
            } else {
                dataBinding.tvLogin.isEnabled = dataBinding.etCode.length() == 6 && dataBinding.etMobile.length() == 11
                if (!inCountDown) {
                    dataBinding.tvGetCode.isEnabled = it?.length == 11
                }
            }
        }

        dataBinding.etCode.doAfterTextChanged {
            dataBinding.ivDelCode.isVisible = !it.isNullOrEmpty()
            if (viewModel.accountLoginType.value == true) {
                dataBinding.tvLogin.isEnabled = !it.isNullOrEmpty() && dataBinding.etMobile.length() > 0
            } else {
                dataBinding.tvLogin.isEnabled = dataBinding.etCode.length() == 6 && dataBinding.etMobile.length() == 11
            }
        }
        viewModel.accountLoginType.observe(this, {
            if (it) {
                dataBinding.vIndicator.animate().translationX(0f).setDuration(250).start()
                dataBinding.etCode.filters = arrayOf(InputFilter.LengthFilter(16))
                dataBinding.etCode.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD
                dataBinding.etCode.hint = "请输入密码"
                dataBinding.ivPassVisible.isSelected = false
                dataBinding.etCode.transformationMethod = PasswordTransformationMethod.getInstance()
            } else {
                dataBinding.vIndicator.animate().translationX(dataBinding.tvAccountLabel.width.toFloat()).setDuration(250).start()
                dataBinding.etCode.inputType = InputType.TYPE_CLASS_NUMBER
                dataBinding.etCode.hint = "请输入验证码"
                dataBinding.etCode.transformationMethod = HideReturnsTransformationMethod.getInstance()
                dataBinding.etCode.filters = arrayOf(InputFilter.LengthFilter(6))
            }
            val temp = dataBinding.etCode.text.toString()
            dataBinding.etCode.setText(viewModel.tempPwdText)
            dataBinding.etCode.setSelection(dataBinding.etCode.length())
            viewModel.tempPwdText = temp
        })

        viewModel.thirdPartLoginResult.observe(this, {
            when (it) {
                AppConstant.CODE_NO_BIND -> {
                    startActivityAndFinish(BindingActivity::class.java) { intent ->
                        intent.putExtra("bind_type", mSelectedBindType)
                        intent.putExtra("bind_openid", viewModel.openId ?: "")
                    }
                }
                AppConstant.CODE_GO_SET_PWD -> startActivityAndFinish(SetPwdActivity::class.java) { intent ->
                    intent.putExtra("token", viewModel.token)
                }
                200 -> finish()
            }
        })
        viewModel.getCodeResult.observe(this, {
            if (it) {
                toast("验证码获取成功")
                dataBinding.tvGetCode.isEnabled = false
                launch {
                    (60 downTo 0).asFlow().onEach { index ->
                        inCountDown = true
                        dataBinding.tvGetCode.text = "重新获取${index}S"
                        delay(1000)
                    }.collectLatest {
                        inCountDown = false
                        dataBinding.tvGetCode.text = "获取验证码"
                        dataBinding.tvGetCode.isEnabled = false
                    }
                }
            }
        })
        viewModel.accountLoginType.value = true
    }

    fun onClick(v: View) {
        when (v.id) {
            R.id.ivClose -> finish()
            R.id.tvAccountLabel -> {
                viewModel.accountLoginType.value = true
            }
            R.id.tvMobileLabel -> {
                viewModel.accountLoginType.value = false
            }
            R.id.ivDelMobile -> dataBinding.etMobile.setText("")
            R.id.ivDelCode -> dataBinding.etCode.setText("")
            R.id.ivPassVisible -> {
                dataBinding.ivPassVisible.isSelected = !dataBinding.ivPassVisible.isSelected
                if (dataBinding.ivPassVisible.isSelected) {
                    dataBinding.etCode.transformationMethod = HideReturnsTransformationMethod.getInstance()
                } else {
                    dataBinding.etCode.transformationMethod = PasswordTransformationMethod.getInstance()
                }
                dataBinding.etCode.setSelection(dataBinding.etCode.length())
            }
            R.id.tvGetCode -> {
                viewModel.getCode(dataBinding.etMobile.text.toString())
            }
            R.id.tvLogin -> {
                viewModel.login(dataBinding.etMobile.text.toString(), dataBinding.etCode.text.toString())
            }
            R.id.tvRegister, R.id.tvRegisterNow -> {
                startActivity(Intent(this, RegisterActivity::class.java))
            }
            R.id.tvForgetPassword -> {
                startActivity(Intent(this, ForgetPwdActivity::class.java))
            }
            R.id.tvWXLogin -> {
                mSelectedBindType = 0
                if (!wxApi.value.isWXAppInstalled) {
                    toast("请先安装微信")
                    return
                }
                val req = SendAuth.Req()
                req.scope = "snsapi_userinfo"
                req.state = "snsapi_login_lnint"
                wxApi.value.sendReq(req)
            }
            R.id.tvQQLogin -> {
                mSelectedBindType = 1
                //如果session不可用，则登录，否则说明已经登录
                AM.mTencent?.login(this, "all", mListener)
            }
            R.id.tvProtocol -> {
                val intent = Intent(this, BrowserActivity::class.java)
                intent.putExtra(BrowserActivity.KEY_URL, NetConstant.BASE_URL + "/home/html/helpCenterDetail?id=44")
                startActivity(intent)
            }
        }
    }

    private inner class BaseUiListener : IUiListener {
        //这个类需要实现三个方法 onComplete（）：登录成功需要做的操作写在这里
        // onError onCancel 方法具体内容自己搜索
        override fun onComplete(response: Any?) {
            if (null == response) {
                toast("返回为空, 登录失败")
                return
            }
            val jb = response as JSONObject
            if (jb.length() == 0) {
                toast("返回为空, 登录失败")
                return
            }
            try {
                val openID = jb.getString("openid") //openid用户唯一标识
                val accessToken = jb.getString("access_token")
                val expires = jb.getString("expires_in")
                if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openID)) {
                    mSelectedBindOpenId = openID
                    AM.mTencent?.openId = openID
                    AM.mTencent?.setAccessToken(accessToken, expires)
                    viewModel.wxOrQQLogin("qq", openID)
                }
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }

        override fun onError(uiError: UiError) {
            toast(uiError.errorMessage)
        }

        override fun onCancel() {}
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, mListener)
        }
    }

    @Subscribe
    fun onEvent(event: WeChatAuthEvent) {
        mSelectedBindOpenId = event.openId
        viewModel.wxOrQQLogin("wx", event.openId)
    }
}